/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-05-09 15:25:26
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-21 13:59:19
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/history_info/history_info_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:bruno/bruno.dart';
import 'package:dart_date/dart_date.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/data_type_config.dart';
import 'package:yt_devops/model/device_obj/properties_model.dart';
import 'package:yt_devops/model/device_obj/spec/double_spec.dart';
import 'package:yt_devops/pages/common/select_page/select_page_binding.dart';
import 'package:yt_devops/pages/common/select_page/select_page_model.dart';
import 'package:yt_devops/pages/common/select_page/select_page_view.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/func_utils.dart';

class HistoryInfoController extends GetxController {
  late DeviceTabController tabController;
  DeviceServices deviceServices = Get.find<DeviceServices>();
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  List<PropertiesModel> propertyList = [];

  DateTime date = DateTime.now();

  Map? dataPoint;

  List<String> timeList = [];

  List dataSourceList = [];

  bool isYxisTypeIsValue = true;

  PropertiesModel? propperty;

  late int productId;

  @override
  void onInit() {
    tabController = Get.find<DeviceTabController>(
        tag: Get.arguments['deviceId'].toString());
    productId = Get.arguments['productId'];
    initData();
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  initData() => Configs.httpClient.requestWithLoading(() async {
        getPropertyList();
        initChartData();
      });

  initChartData() {
    timeList = ChartXDate.getDataByDuration(
      duration: const Duration(minutes: 4),
      initList: timeList,
      startTime: date.startOfDay,
      endTime: date.endOfDay,
    );
    var len = timeList.length - dataSourceList.length;
    for (var i = 0; i < len; i++) {
      dataSourceList.add(null);
    }

    update();
  }

  getChartData() async {
    if(dataPoint == null || dataPoint!['paramCode'] == null){
      refreshController.refreshCompleted();
      return;
    }
      var map = {
        'deviceId': tabController.deviceId,
        'key': dataPoint!['paramCode'],
        'startTime': date.startOfDay.toString().substring(0, 19),
        'endTime': date.endOfDay.toString().substring(0, 19)
      };
      Log.d('map===' + map.toString());
      showLoading();
      var data = await deviceServices.queryDeviceDataForHistoryList(map,onError:(error){
        dismissLoading();
        refreshController.refreshCompleted();
        handleException(error);
        return false;
      });
     dismissLoading();
      refreshController.refreshCompleted();
      timeList = [];
      dataSourceList.clear();
      propperty = findTargetProperty(dataPoint!['paramCode']);
      if (!FuncUtils.isListEmpty(data)) {
        isYxisTypeIsValue =
            propperty?.dataType?.type == DataTypeConfigEnum.double ||
                propperty?.dataType?.type == DataTypeConfigEnum.int ||
                propperty?.dataType?.type == DataTypeConfigEnum.long;

        // 数据处理
        for (var element in data) {
          var value;
          if (propperty?.dataType?.type == DataTypeConfigEnum.enumType) {
            if (element['value'] is double) {
              element['value'] = element['value'].toInt();
            }
            var map = (propperty?.dataType?.specs ?? {}) as Map;
            value = map[element['value'].toString()];
          } else {
            value = element['value'];
          }
          dataSourceList.add(value);
          timeList.add(element['eventTs']);
        }
      }
      timeList = ChartXDate.getDataByDuration(
        duration: const Duration(minutes: 4),
        initList: timeList,
        startTime: date.startOfDay,
        endTime: date.endOfDay,
      );
      var len = timeList.length - dataSourceList.length;
      for (var i = 0; i < len; i++) {
        dataSourceList.add(null);
      }
      update();
  }


  Future getPropertyList() async {
    var data = await deviceServices.getDeviceProperty({'productId': productId});
    propertyList = data['properties']
        .map<PropertiesModel>((e) => PropertiesModel.fromJson(e))
        .toList();
  }

  selectDataPoint() {
    Get.to(SelectPagePage<Map<dynamic, dynamic>>(),
        binding: SelectPageBinding<Map<dynamic, dynamic>>(),
        arguments: SelectPageProp(
          ResKey.deviceDataCollectionPoints.tr,
          getIdByKey: (Map map) => map['paramCode'],
          getNameKey: (Map map) => map['paramName'],
          searchKey: 'modelName',
          initSelectValues:
              dataPoint == null ? <Map<dynamic, dynamic>>[] : [dataPoint!],
          service: (params) => deviceServices.deviceParamList({
            'modelName': params.extra?['modelName'],
            'deviceId': tabController.deviceId
          }),
        ))?.then((value) {
      if (value is Map) {
        dataPoint = value;
        update();
        getChartData();
      }
    });
  }

  selectTime(BuildContext context, DateTime value) {
    BrnDatePicker.showDatePicker(
      context,
      pickerMode: BrnDateTimePickerMode.date,
      pickerTitleConfig: BrnPickerTitleConfig(
          titleContent: value.format(TimeFormated.dateShowFromated)),
      dateFormat: 'yyyy-MM-dd',
      initialDateTime: value,
      onConfirm: (startDateTime, list) {
        date = startDateTime;
        update();
        getChartData();
      },
    );
  }

  PropertiesModel findTargetProperty(String id) {
    return propertyList.firstWhere((element) => element.id == id);
  }

  String? unit(PropertiesModel? model) {
    var spec = model?.dataType?.specs;
    if (spec is DoubleSpec) {
      return spec.unit;
    }
    return null;
  }

  getEnumArray(PropertiesModel? model) {
    var enumList = [];
    var spec = model?.dataType?.specs;
    if (spec is Map) {
      enumList = spec.values.toList();
      enumList.insert(0, '');
    }
    return enumList;
  }

  int getAxisInterval(List list) {
    var interver = 1;
    if (list.length > 2) {
      var duration = Duration(
          milliseconds: DateTime.tryParse(list[1])!.millisecondsSinceEpoch -
              DateTime.tryParse(list[0])!.millisecondsSinceEpoch);
      var starOfDay = DateTime.now().startOfDay;
      var endtime = starOfDay.addHours(4);

      interver =
          (endtime.millisecondsSinceEpoch - starOfDay.millisecondsSinceEpoch) ~/
              duration.inMilliseconds;
    }

    return interver;
  }
}
